'use strict'
let  resultmodel=require('../model/index');

let fn_list = async (ctx, next) => {
    let keyword = ctx.request.query.keyword || '';
    if (keyword) {
        let list;
        list = await resultmodel.User.findAll({
            where: {
                [resultmodel.Op.or]: [
                    { id: isNaN(keyword) ? 0 : parseInt(keyword) },
                    { Name: keyword },
                    { sex: keyword},
                    { sum:parseInt(keyword)}
                ]
            },
            order:['id']
        })
        ctx.body = {
            code: 1000,
            data: list,
            msg: '请求成功'
        }
    } else {
        let list = await resultmodel.User.findAll({
            order:['id']
        });
        ctx.body = {
            code: 1000,
            data: list,
            msg: '请求成功'
        }
    }
}
//查询
let fn_getbyid = async (ctx, next) => {
    let id = ctx.request.params.id;
    let user = await resultmodel.User.findByPk(id);
    if (user) {
        ctx.body = {
            code: 1000,
            data: user,
            msg: '查找成功'
        }
    } else {
        ctx.body = {
            code: 900,
            data: '',
            msg: '查找内容不存在'
        }
    }
}
let fn_post =async (ctx, next) => {
    let obj = ctx.request.body;
    await resultmodel.User.create(obj);
    ctx.body = obj;
}
//修改
let fn_put =async (ctx, next) => {
    let id = ctx.request.params.id;
    let obj = ctx.request.body;
    let product = await resultmodel.User.findByPk(id);
    if (product) {
        resultmodel.User.update(obj,{
            where:{
                id:id
            }
        })
        ctx.body = {
            code: 1000,
            data: product,
            msg: '修改成功'
        }
    } else {
        ctx.body = {
            code: 300,
            data: '',
            msg: '修改失败'
        }
    }
}
//删除
let fn_delete =async (ctx, next) => {
    let id = ctx.request.params.id;
    let product = await resultmodel.User.findByPk(id);
    if (product) {
        resultmodel.User.destroy({
            where:{
                id:id
            }
        })
        ctx.body = {
            code: 1000,
            data: { id },
            msg: '删除成功'
        }
    } else {
        ctx.body = {
            code: 500,
            data: null,
            msg: '删除失败'
        }
    }
}
module.exports={
    'get /user':fn_list,
    'get /user/:id':fn_getbyid,
    'post /user':fn_post,
    'put /user/:id':fn_put,
    'delete /user/:id':fn_delete
}